import { getToken } from "./userAuth";
// 跳转
export function navigateTo(path) {
    uni.navigateTo({
        url:"/pages/"+path
    });
}

// 跳转
export function switchTab(path){
    uni.switchTab({
        url:"/pages/"+path
    });
}

// 跳转
export function reLaunch(path){
    uni.reLaunch({
        url:"/pages/"+path
    });
}

// 需要判断登录的跳转
export function loginNavigateTo(path){
    if (!getToken()) {
        navigateTo("login/index");
        return false;
    }
    navigateTo(path);
}

// 跳转webView
export function jumpWebView(url){
    url = encodeURIComponent(url);
    navigateTo("utils/webView?url=" + url)
}

/**
 * 自动消失的提示窗
 */
export function toast(msg){
    uni.showToast({
        icon: 'none',
        title: msg,
        duration: 2000
    });
}
/**
 * 将对象转为url参数
 * @param data
 * @param isPrefix
 */
export function queryParams(data, isPrefix = false) {
    let prefix = isPrefix ? '?' : '';
    let _result = [];
    for (let key in data) {
        let value = data[key];
        // 去掉为空的参数
        if (['', undefined, null].includes(value)) {
            continue
        }
        if (value.constructor === Array) {
            value.forEach(_value => {
                _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
            })
        } else {
            _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
        }
    }

    return _result.length ? prefix + _result.join('&') : ''
}

/**
 * 事件防抖
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result;

    const later = function() {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp;

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null;
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null
            }
        }
    };

    return function(...args) {
        context = this;
        timestamp = +new Date();
        const callNow = immediate && !timeout;
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null
        }

        return result
    }
}



// 拍照
export function createCameraContext() {
    uni.createCameraContext()({
        
    });
}